import pygame
import sys
import random
import time

# 初始化pygame
pygame.init()

# 游戏常量
SCREEN_WIDTH = 480
SCREEN_HEIGHT = 800
FPS = 60

# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)

# 创建游戏窗口
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("简易飞机大战")
clock = pygame.time.Clock()


# 玩家飞机类
class Player(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        # 创建一个简单的飞机形状（绿色三角形）
        self.image = pygame.Surface((50, 40), pygame.SRCALPHA)
        pygame.draw.polygon(self.image, GREEN, [(25, 0), (0, 40), (50, 40)])
        self.rect = self.image.get_rect()
        self.rect.centerx = SCREEN_WIDTH // 2
        self.rect.bottom = SCREEN_HEIGHT - 10
        self.speed_x = 0
        self.shoot_delay = 250
        self.last_shot = pygame.time.get_ticks()

    def update(self):
        self.speed_x = 0
        # 检查按键状态
        keystate = pygame.key.get_pressed()
        if keystate[pygame.K_LEFT]:
            self.speed_x = -8
        if keystate[pygame.K_RIGHT]:
            self.speed_x = 8
        # 射击
        if keystate[pygame.K_SPACE]:
            self.shoot()

        self.rect.x += self.speed_x
        # 限制在屏幕内
        if self.rect.left < 0:
            self.rect.left = 0
        if self.rect.right > SCREEN_WIDTH:
            self.rect.right = SCREEN_WIDTH

    def shoot(self):
        now = pygame.time.get_ticks()
        if now - self.last_shot > self.shoot_delay:
            self.last_shot = now
            bullet = Bullet(self.rect.centerx, self.rect.top)
            all_sprites.add(bullet)
            bullets.add(bullet)


# 敌人类
class Enemy(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        # 创建一个简单的敌机形状（红色矩形）
        self.image = pygame.Surface((40, 30))
        self.image.fill(RED)
        self.rect = self.image.get_rect()
        self.rect.x = random.randrange(SCREEN_WIDTH - self.rect.width)
        self.rect.y = random.randrange(-100, -40)
        self.speed_y = random.randrange(3, 7)
        self.speed_x = random.randrange(-2, 2)

    def update(self):
        self.rect.y += self.speed_y
        self.rect.x += self.speed_x
        # 超出屏幕后重新出现
        if (self.rect.top > SCREEN_HEIGHT + 10 or
                self.rect.left < -25 or
                self.rect.right > SCREEN_WIDTH + 25):
            self.rect.x = random.randrange(SCREEN_WIDTH - self.rect.width)
            self.rect.y = random.randrange(-100, -40)
            self.speed_y = random.randrange(3, 7)


# 子弹类
class Bullet(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super().__init__()
        # 创建子弹（白色小矩形）
        self.image = pygame.Surface((5, 15))
        self.image.fill(WHITE)
        self.rect = self.image.get_rect()
        self.rect.centerx = x
        self.rect.bottom = y
        self.speed_y = -15

    def update(self):
        self.rect.y += self.speed_y
        # 超出屏幕顶端则删除
        if self.rect.bottom < 0:
            self.kill()


# 创建精灵组
all_sprites = pygame.sprite.Group()
enemies = pygame.sprite.Group()
bullets = pygame.sprite.Group()

# 创建玩家
player = Player()
all_sprites.add(player)

# 创建初始敌人
for i in range(8):
    enemy = Enemy()
    all_sprites.add(enemy)
    enemies.add(enemy)

# 游戏分数
score = 0

# 游戏主循环
running = True
game_over = False

while running:
    if not game_over:
        # 保持循环以正确的速度运行
        clock.tick(FPS)

        # 处理事件
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

        # 更新精灵
        all_sprites.update()

        # 检测子弹和敌人的碰撞
        hits = pygame.sprite.groupcollide(enemies, bullets, True, True)
        for hit in hits:
            score += 10
            enemy = Enemy()
            all_sprites.add(enemy)
            enemies.add(enemy)

        # 检测敌人和玩家的碰撞
        hits = pygame.sprite.spritecollide(player, enemies, True)
        if hits:
            game_over = True
            # 创建一个新敌人替换被碰撞的敌人
            enemy = Enemy()
            all_sprites.add(enemy)
            enemies.add(enemy)

        # 绘制
        screen.fill(BLACK)
        all_sprites.draw(screen)

        # 显示分数
        font = pygame.font.SysFont(None, 36)
        text = font.render(f"分数: {score}", True, WHITE)
        screen.blit(text, (10, 10))

        # 更新屏幕
        pygame.display.flip()
    else:
        # 游戏结束画面
        screen.fill(BLACK)
        font = pygame.font.SysFont(None, 72)
        text = font.render("游戏结束", True, RED)
        text_rect = text.get_rect(center=(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2))
        screen.blit(text, text_rect)

        font_small = pygame.font.SysFont(None, 36)
        score_text = font_small.render(f"最终分数: {score}", True, WHITE)
        score_rect = score_text.get_rect(center=(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2 + 50))
        screen.blit(score_text, score_rect)

        restart_text = font_small.render("按R键重新开始", True, WHITE)
        restart_rect = restart_text.get_rect(center=(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2 + 100))
        screen.blit(restart_text, restart_rect)

        pygame.display.flip()

        # 处理游戏结束时的事件
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_r:
                    # 重置游戏
                    game_over = False
                    score = 0

                    # 清除所有精灵
                    for sprite in all_sprites:
                        sprite.kill()

                    # 重新创建玩家
                    player = Player()
                    all_sprites.add(player)

                    # 重新创建敌人
                    for i in range(8):
                        enemy = Enemy()
                        all_sprites.add(enemy)
                        enemies.add(enemy)

# 退出游戏
pygame.quit()
sys.exit()
